
package com.thinkgem.jeesite.common.component.redis.service;

import java.util.Date;

import org.apache.commons.lang3.time.DateFormatUtils;

import redis.clients.jedis.Jedis;

public class PSubHandler{

	public PSubHandler(String clientId, Jedis jedis) {
	    this.clientId = clientId;
	    this.jedis = jedis;
    }

	public PSubHandler(Jedis jedis){
		this.clientId = getClientId();
		this.jedis = jedis;
	}

	public String getClientId() {
    	return clientId;
    }

	public void setClientId(String clientId) {
    	this.clientId = clientId;
    }

	public Jedis getJedis() {
    	return jedis;
    }

	public void setJedis(Jedis jedis) {
    	this.jedis = jedis;
    }

	public static String getSubscribeCenter() {
    	return SUBSCRIBE_CENTER;
    }

	public static String getMessageTxid() {
    	return MESSAGE_TXID;
    }

	private void message(String channel,String message){
		String time = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
		System.out.println("message receive:" + message + ",channel:" + channel + "..." + time);
	}

	public void handle(String channel,String message){
		int index = message.indexOf("/");
		if(index < 0){
			return;
		}
		Long txid = Long.valueOf(message.substring(0,index));
		String key = clientId + "/" + channel;
		while(true){
				String lm = jedis.lindex(key, 0);//获取第一个消息
				if(lm == null){
					break;
				}
				int li = lm.indexOf("/");
				//如果消息不合法，删除并处理
				if(li < 0){
					String result = jedis.lpop(key);//删除当前message
					//为空
					if(result == null){
						break;
					}
					message(channel, lm);
					continue;
				}
				Long lxid = Long.valueOf(lm.substring(0,li));//获取消息的txid
				//直接消费txid之前的残留消息
				if(txid >= lxid){
					jedis.lpop(key);//删除当前message
					message(channel, lm);
					continue;
				}else{
					break;
				}
		}
	}
	
	public void subscribe(String channel){
		String key = clientId + "/" + channel;
		boolean exist = jedis.sismember(SUBSCRIBE_CENTER,key);
		if(!exist){
			jedis.sadd(SUBSCRIBE_CENTER, key);
		}
	}
	
	public void unsubscribe(String channel){
		String key = clientId + "/" + channel;
		jedis.srem(SUBSCRIBE_CENTER, key);//从“活跃订阅者”集合中删除
		jedis.del(key);//删除“订阅者消息队列”
	}

	private String clientId="_-default-client-_";
	private Jedis jedis;

	public static final String SUBSCRIBE_CENTER = "_-subscribe-center-_";
	public static final String MESSAGE_TXID = "_-message-txid-_";

}